package com.vhall.component.service.account.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vhall.component.entity.account.dto.CheckRiskMatchDTO;
import com.vhall.component.entity.guosen.entity.GuosenIfcPeHoldEntity;
import com.vhall.component.entity.room.dto.RoomsEntityDTO;
import com.vhall.component.entity.room.enums.LiveWatchLimitCheckEnum;
import com.vhall.component.entity.room.vo.LiveWatchCheckRequestVO;
import com.vhall.component.entity.room.vo.LiveWatchCheckResponseVO;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.plugin.core.service.GuoXinService;
import com.vhall.component.service.guosen.GuosenIfcPeHoldService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * CommonLiveWatchCheck-
 *
 * @author xing.wang
 * @date 2023/8/19
 */
@Slf4j
@Component
public class CommonLiveWatchCheck {
    @Resource
    private GuoXinService guoXinService;
    @Resource
    private GuosenIfcPeHoldService guosenIfcPeHoldService;

    /**
     * 检查 资金账户绑定/交易登录
     * @return true 绑定了资金账户 或 登录了交易账号,false 没交易登录,也没有绑定资金账户
     */
    public boolean checkUserFundAccountBindAndTransactionLogin() {
        Token token = TokenThreadLocal.getToken();
        String fundId = token.getFundId();
        String custId = token.getCustId();
        return StrUtil.isNotBlank(fundId) || StrUtil.isNotBlank(custId);
    }

    /**
     * 检查是否进行了交易登录
     * @return
     */
    public boolean checkUserFundAccountBind() {
        Token token = TokenThreadLocal.getToken();
        String custId = token.getCustId();
        return StrUtil.isNotBlank(custId);
    }

    /**
     * 检查是否进行了交易登录
     * @return
     */
    public boolean checkUserTransactionLogin(){
        Token token = TokenThreadLocal.getToken();
        String fundId = token.getFundId();
        return StrUtil.isNotBlank(fundId);
    }

    /**
     * 进行观众观看适当性校验
     * @param vo
     * @param roomInfoById
     * @return
     */
    public LiveWatchCheckResponseVO checkUserRiskMatch(LiveWatchCheckRequestVO vo, RoomsEntityDTO roomInfoById) {
        LiveWatchCheckResponseVO result = new LiveWatchCheckResponseVO();
        Integer liveType = roomInfoById.getLiveContentType();
        Token token = TokenThreadLocal.getToken();
        CheckRiskMatchDTO dto = new CheckRiskMatchDTO();
        String fundId = token.getFundId();
        String custId = token.getCustId();
        Integer ilId = roomInfoById.getIlId();
        List<GuosenIfcPeHoldEntity> ifcPeHoldEntityList = getAccountGuosenIfcPeHoldEntities(fundId, custId, ilId);
//        适当性豁免判定
        if (CollUtil.isNotEmpty(ifcPeHoldEntityList)) {
            result.setCheckResult(LiveWatchLimitCheckEnum.CHECK_PASSED.getValue());
            return result;
        }
        if (StrUtil.isNotBlank(fundId) && !"0".equals(fundId)) {
            dto.setCustid(fundId);
        }else{
            dto.setCustid(custId);
        }
        dto.setLiveType(liveType);
        dto.setHgtzz(Integer.valueOf(roomInfoById.getQualifiedInvestorRequirements()));
        dto.setPrdInvestPeriod(Integer.valueOf(roomInfoById.getInvestLimit()));
        dto.setPrdInvestType(Integer.valueOf(roomInfoById.getInvestType()));
        dto.setPrdRiskLevel(Integer.valueOf(roomInfoById.getRiskLive()));
        dto.setPrdUseCase(roomInfoById.getPermissions());
        dto.setRandomKey(vo.getRandomKey());
        dto.setUserCode(token.getThirdPartyUserId());
        dto.setChannel(vo.getChannel());
        JSONObject checkRiskMatchJson = guoXinService.checkRiskMatch(dto);
        if (Objects.isNull(checkRiskMatchJson)) {
            result.setCheckResult(LiveWatchLimitCheckEnum.CHECK_PASSED.getValue());
        }else{
            String type = checkRiskMatchJson.getString("type");
            String url = checkRiskMatchJson.getString("url");
            String notice = checkRiskMatchJson.getString("notice");
            result.setCheckResult(LiveWatchLimitCheckEnum.CHECK_FAIL.getValue());
            result.setType(type);
            result.setUrl(url);
            result.setNotice(notice);
        }

        return result;
    }

    /**
     * 使用资金账号和客户号获取客户是否购买过对应房间有适当性豁免资格的私募商品
     * @param fundId 资金账号
     * @param custId 客户号
     * @param ilId 房间id
     * @return
     */
    private List<GuosenIfcPeHoldEntity> getAccountGuosenIfcPeHoldEntities(String fundId, String custId, Integer ilId) {
        LambdaQueryWrapper<GuosenIfcPeHoldEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .exists(" select rpr.id from room_prod_relation rpr " +
                        " where rpr.ofcode=guosen_ifc_pe_hold.ofcode " +
                        " and rpr.type=0 " +
                        " and rpr.il_id="+ ilId)
                .and(w->w.eq(GuosenIfcPeHoldEntity::getCustid, custId)
                        .or()
                        .eq(GuosenIfcPeHoldEntity::getFundid, fundId));
        return guosenIfcPeHoldService.list(queryWrapper);
    }
}
